/*************************单个评论对象***************************/
let oneComment = function (shareId, pareNode) {
    this.shareId = shareId;
    this.page = 0;
    this.pareNode = pareNode;
    this.time = null;
};
oneComment.prototype.ajax = function () {
    let url = "/comment/getList",
        data = {
            "pageNum": this.page++,
            "pageSize": 1,
            "orderByField": "createTime",
            "shareId": this.shareId,
            "ascend": true
        },
        method = "POST";
    return ajax_base(data, url, method, "Json");
};

oneComment.prototype.update = function (obj) {
    // this.pareNode.appendChild(this.div);
    let list = this.pareNode.children[3].getElementsByTagName("a");
    let img = list[0].getElementsByTagName("img")[0];
    let name = list[1];
    let content = list[3];
    img.src = obj.owner.userLogo;
    name.innerHTML = obj.owner.userName;
    content.innerHTML = obj.content;
};

oneComment.prototype.showInLoop = function () {
    let that = this;
    this.time = setInterval(function () {
        if (that.page > 5) {
            that.page = 0;
        }
        that.ajax().then(function (data) {
            if (data.obj) {
                that.update(data.obj[0]);
            }
        })
    }, 3000);
};
oneComment.prototype.stopLoop = function () {
    clearInterval(this.time);
};
/**************以下为下拉的详细评论的总对象**************/
//单个评论节点
let CommentNode = function () {
    this.shareNodeWrapperNode = null;
    this.oneCommentNode = document.createElement("div");
    this.oneCommentNode.className = "share-comment";
};
CommentNode.prototype.getOneNode = function (array, i) {
    let response = "",
        responseContent = "";
    if (array[i].replyUser) {
        response = "回复";
        responseContent = array[i].replyUser.userName;
    }
    this.oneCommentNode.id = array[i].commentId + "commentId";
    this.oneCommentNode.innerHTML =
        '<div class="share-comment-header">' +
        '<a class="logo">' +
        '<img src="' + array[i].owner.userLogo.thumbUrl + '">' +
        '</a>' +
        '<a class="name" id="' + array[i].owner.userId + 'ownerUserName' + '">' + array[i].owner.userName + '</a>' +
        '<a class="response">&nbsp;' + response + '&nbsp;</a>' +
        '<a class="">' + responseContent + '</a>' +
        '<a class="share-commentNode-floor">' + array[i].createTime + '</a>' +
        '</div>' +
        '<div class="share-comment-middle"><a class="share-comment-text">' + array[i].content + '</a></div>' +
        '<div class="share-comment-bottom">' +
        '<a class="share-comment-thumbsUp"><i class="fa fa-thumbs-o-up"></i><span class="share-comment-thumbsUp-number">0</span></a>' +
        '<a class="share-comment-reply">回复<i class="fa fa-comments-o"></i></a>' +
        '<a class="share-comment-report">举报<i class="fa fa-flag"></i></a>' +
        '</div>';
    this.addPraise();
    this.addAbuse();
    return this.oneCommentNode;
};
//单个评论点赞功能
CommentNode.prototype.addPraise = function () {
    this.oneCommentNode.querySelector(".fa-thumbs-o-up").onclick = (event) => {   //es6语法，剪括号函数
        let node = event.target;
        let point = node.parentNode.parentNode.parentNode; // 当前评论用户节点
        let pointId = parseInt(point.id);
        let url = "/comment/praise";
        let direction = true;
        let data = {
                commentId: pointId,
                userId: loginUserId,
                direction: direction
            },
            method = "POST",
            that = this;
        ajax_base(data, url, method, "Json").then(function (data) {
                if (data.success) {
                    that.praiseColor(node);
                }
            }
        )
    }
};
//设置点赞的节点实现效果
CommentNode.prototype.praiseColor = function (node) {
    let next = node.nextSibling;
    if (node.className === "fa fa-thumbs-up") {
        node.className = "fa fa-thumbs-o-up";
        next.innerText = parseInt(next.innerText) - 1;
    } else {
        node.className = "fa fa-thumbs-up";
        next.innerText = parseInt(next.innerText) + 1;
    }
};
//单个评论节点举报功能
CommentNode.prototype.addAbuse=function () {
    this.oneCommentNode.querySelector(".share-comment-report").onclick = (event) => {   //es6语法，剪括号函数
        let node = event.target;
        let point = node.parentNode.parentNode; // 当前评论用户节点
        let commentId = parseInt(point.id);
        let modelAbuse = new ModelNormal();
        modelAbuse.ajax_send = function () {
            let data = {
                    commentId: commentId,
                    userId: loginUserId,
                    reason: this.pareNode.querySelector(".textarea-share").value  //这个是模态框弹出的内容的值
                },
                url = "/comment/abuse",
                method = "POST";
            return ajax_base(data, url, method, "notJson");
        };
        modelAbuse.setText("评论举报","举报的原因");
        modelAbuse.setDisplay("举报");
    }
};
/*下拉评论的单个评论总和*/
let CommentNodeList = function (shareId) {
    this.shareId = shareId;
    this.page = 1;
    this.shareNodeWrapper = document.createElement('div');
    this.shareNodeWrapper.className = "share-node-wrapper";
    this.shareNodeTotal = document.createElement('div');
    this.shareNodeTotal.className = "share-node-total";
    this.parentPoint = null;
};
CommentNodeList.prototype.setParentPoint = function (parentPoint) {
    this.parentPoint = parentPoint;
};
//设置评论列表的内部html
CommentNodeList.prototype.setCommentInnerHtml = function (array) {
    for (let i = 0; i < array.length; i++) {
        this.shareNodeTotal.appendChild(new CommentNode().getOneNode(array, i));
    }
};
CommentNodeList.prototype.getComment = function (array) {
    if (array !== null)
        this.setCommentInnerHtml(array);
    this.shareNodeWrapper.appendChild(this.shareNodeTotal);
    return this.shareNodeWrapper;
};
//这个为更新评论
CommentNodeList.prototype.upDate = function (array) { //func为父节点评论更新后的监听回复
    this.setCommentInnerHtml(array);
    this.parentPoint.addResponseEvent();
};
CommentNodeList.prototype.setPage = function () {
    let that = this;
    let model = this.shareNodeTotal;
    tool.on(model, "scroll", function () { //用到tool的定时器
        clearTimeout(tool.timer3);
        let height = model.scrollHeight - model.clientHeight;
        if (height === model.scrollTop) {
            console.log("请求开始");
            //缓存
            tool.timer3 = setTimeout(function () {
                //分页
                that.ajax_getList().then(function (data) {
                    that.upDate(data.obj);
                    that.adjustHeight();
                })
            }, 50)
        }
    })
};
CommentNodeList.prototype.adjustHeight = function (node) { //注意:node 为this.pareNode.children[2].children[3]
    if (this.shareNodeTotal.innerHTML === '')
        node.style.display = "block";
    let length = this.shareNodeTotal.children.length;
    if (length > 3) {
        this.shareNodeWrapper.style.height = "200px"
    } else {
        this.shareNodeWrapper.style.height = length * 72 + "px";
    }
};
CommentNodeList.prototype.ajax_getList = function () {
    let that = this,
        url = "/comment/getList",
        data = {
            "pageNum": this.page,
            "pageSize": 5,
            "orderByField": "createTime",
            "shareId": this.shareId,
            "ascend": "true"
        },
        method = "POST",
        func = function (data) { //改变data
            if (data.obj && data.obj[0]) {
                if (that.shareNodeTotal.innerHTML !== "") {
                    let commentId = parseInt(that.shareNodeTotal.children[that.shareNodeTotal.children.length - 1].id);
                    if (data.obj.length === 5)
                        that.page++;
                    let final_data = {
                        obj: []
                    };
                    for (let i = 0; i < data.obj.length; i++) {
                        if (commentId < data.obj[i].commentId) {
                            final_data.obj.push(data.obj[i]);
                        }
                    }
                    data = final_data;
                } else {
                    that.page++;
                }
            }
            return data;
        };
    return ajax_base(data, url, method, "Json", func);
};
/*下划线*/
let BottomLine = function () {
    this.BottomLine = document.createElement("div");
    this.BottomLine.className = "share-header-bottom";
    this.BottomLine.innerHTML = "";
    return this.BottomLine;
};
/*下拉菜单的提交评论*/
let ResponseComment = function (shareId) {
    this.shareId = shareId;
    this.responseTo = document.createElement('div');
    this.responseTo.className = "responseTo-all";
    this.sendTo = document.createElement('div');
    this.sendTo.className = "share-send-text";
    this.setResponse();
};
ResponseComment.prototype.setResponse = function () {
    this.responseTo.innerHTML =
        '<div class="logo"><img src="' + loginImg + '"></div>' +
        '<div class="commentTo-send">' +
        '<div class="commentTo-send-text" contenteditable="true" placeholder="分享你的感受"></div>';

    this.sendTo.innerHTML =
        '<a class="share-send-button">发布</a>' +
        '<a class="share-comment-cancel">清空</a>';
};
//适应宽度
ResponseComment.prototype.bottomCommentAdjust = function (pare, node) {
    node.style.right = -( pare.offsetWidth - node.clientWidth) + "px";
};
//以下为发送评论的代码
ResponseComment.prototype.ajax_sendComment = function (content, targetId) {
    let url = "/comment/new";
    let data = {
        "content": content,
        "atIds": null,
        "shareId": this.shareId,
        "userId": loginUserId,
        "targetId": targetId
    };
    return ajax_base(data, url, "POST", "Json");
};
//发送评论，包括普通评论，回复评论
ResponseComment.prototype.sentComment = function () {
    let commentText,
        commentId;
    let sureSend = this.sendTo.children[0];
    let that = this;
    sureSend.onclick = function () {
        let point = that.responseTo.querySelector(".commentTo-send-text");
        if (point.querySelector(".response-person")) {
            commentText = (point.querySelector(".response-content").innerText).slice(1);
            commentId = parseInt(point.querySelector(".response-person").id);
        } else {
            commentText = point.innerText;
            commentId = "";
        }
        that.ajax_sendComment(commentText, commentId).then(function () {
            that.responseTo.querySelector(".commentTo-send-text").innerText = "";
        })
    };
};

/*下拉菜单的总评论*/
let TotalComment = function (shareId, pareNode) {
    this.pareNode = pareNode;
    this.shareId = shareId;
    this.timer_animate = null;
    this.commentNodeList = new CommentNodeList(shareId);
    this.commentNodeList.setParentPoint(this);
    this.responseComment = new ResponseComment(shareId);
    this.bottomLine = new BottomLine();
    this.div = document.createElement("div");
    this.div.className = "share-bottom TotalComment";//TotalComment用作辅佐标记
    this.div.style.height = "0px";
};
TotalComment.prototype.show = function (type) {
    let that = this;
    this.pareNode.querySelector(".add-comment").onclick = function () {
        if (!that.pareNode.querySelector(".TotalComment")) {
            that.commentNodeList.ajax_getList().then(function (data) {      //ajax请求
                that.initTotal(data.obj);
                if (type === "allShare-hasComment") {    //有单条评论
                    that.showTypeHasComment();
                }
                else if (type === "allShare-zeroComment") { //无单条评论
                    that.showZeroComment();
                } else if (type === "oneShare") {
                    that.showOneShare();
                }
            });
        } else {
            if (type === "allShare-hasComment") {    //有单条评论
                that.showTypeHasComment();
            }
            else if (type === "allShare-zeroComment") { //无单条评论
                that.showZeroComment();
            } else if (type === "oneShare") {
                that.showOneShare();
            }
        }

    };
};
TotalComment.prototype.showTypeHasComment = function () {
    if (this.pareNode.querySelector(".hasComment").style.display === "block" || this.pareNode.querySelector(".hasComment").style.display === "") {
        this._checkNodeTotal_forShowPreBorder();
        this.pareNode.querySelector(".hasComment").style.display = "none";
        this.animateHeight(true, this._getHeightOfBottom())
    } else {
        this._checkNodeTotal_forShowPreBorder();
        let that = this;
        this.animateHeight(false, that._getHeightOfBottom(), function () {
            that.pareNode.querySelector(".hasComment").style.display = "block";
        })
    }
};
TotalComment.prototype.showZeroComment = function () {
    if (this.div.style.height === "0px") {
        this._checkNodeTotal_forShowPreBorder();
        this.animateHeight(true, this._getHeightOfBottom())
    } else {
        this._checkNodeTotal_forShowPreBorder();
        this.animateHeight(false, this._getHeightOfBottom())
    }
};
TotalComment.prototype.showOneShare = function () {
    if (this.div.style.height === "0px") {
        this._checkNodeTotal_forShowPreBorder();
        this.animateHeight(true, this._getHeightOfBottom());
    } else {
        this._checkNodeTotal_forShowPreBorder();
        this.animateHeight(false, this._getHeightOfBottom())
    }
};
TotalComment.prototype.initTotal = function (array, flag) { //flag用于检测是否是oneShare
    this.div.appendChild(this.commentNodeList.getComment(array));
    this.div.appendChild(this.bottomLine);
    this.div.appendChild(this.responseComment.responseTo);
    this.div.appendChild(this.responseComment.sendTo);
    this.pareNode.appendChild(this.div);
    this.commentNodeList.adjustHeight(this.pareNode.querySelector(".share-header-bottom"));
    this.commentNodeList.setPage();
    this.responseComment.bottomCommentAdjust(this.pareNode.querySelector(".commentTo-send"), this.pareNode.querySelector(".commentTo-send-text"));
    this.responseComment.sentComment();
    this.addResponseEvent();
};
//以下为回复评论的代码
TotalComment.prototype.addResponseEvent = function () {
    let that = this,
        replyList = this.pareNode.querySelectorAll(".share-comment-reply"),
        sendText = that.pareNode.querySelector(".commentTo-send-text");
    for (let i = 0; i < replyList.length; i++) {
        replyList[i].onclick = function () {
            sendText.innerHTML = "<a class='response-innerText'>回复 " + "<span class='response-person' id='" + parseInt(this.parentNode.parentNode.id) + "responseToId" + "'>" + this.parentNode.parentNode.children[0].children[1].innerText + "</span>" + "<span class='response-content'>：</span></span></a>";
            sendText.oninput = function () {
                if (this.querySelector(".response-person")) {
                    let text = this.querySelector(".response-content");
                    if (!text) {
                        this.removeChild(this.querySelector(".response-innerText"));
                    }
                }
            };
        }
    }
};
TotalComment.prototype._checkNodeTotal_forShowPreBorder = function (type) {
    if (this.pareNode.querySelector(".share-node-total").innerHTML === "") {
        this.bottomLine.style.display = "none";
    }
};
TotalComment.prototype._getHeightOfBottom = function () {
    if (this.pareNode.querySelector(".share-node-total").innerHTML === "") {
        return parseInt(this.commentNodeList.shareNodeWrapper.style.height) + 91;
    } else {
        return parseInt(this.commentNodeList.shareNodeWrapper.style.height) + 111;
    }
};

TotalComment.prototype.animateHeight = function (flag, height, func) {
    let tem;
    let that = this;
    if (this.timer_animate === null) {
        if (flag) {
            tem = 0;
            that.timer_animate = setInterval(function () {
                if (tem < height) {
                    tem += 5;
                    if (tem > height) {
                        tem = height;
                    }
                    that.div.style.height = tem + "px";
                } else {
                    clearInterval(that.timer_animate);
                    that.timer_animate = null;
                    return null;
                }
            }, 3);
        } else {
            tem = height;
            that.timer_animate = setInterval(function () {
                if (tem > 0) {
                    tem -= 5;
                    if (tem < 0) {
                        tem = 0;
                    }
                    that.div.style.height = tem + "px";
                } else {
                    if (func)
                        func();
                    clearInterval(that.timer_animate);
                    that.timer_animate = null;
                    return null;
                }
            }, 3);
        }
    }
};